package com.lrkj.back.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lrkj.back.service.TbAfficheService;
import com.lrkj.back.vo.KucunWarnVO;
import com.lrkj.back.Const;
import com.lrkj.back.entity.TbEmployee;
import com.lrkj.back.entity.TbFile;
import com.lrkj.back.entity.TbPackageMuban;
import com.lrkj.back.entity.ZsDabao;
import com.lrkj.back.service.TbAdviceService;
import com.lrkj.back.service.TbFileService;
import com.lrkj.back.service.TbPackageMubanService;
import com.lrkj.back.service.TbShiftService;
import com.lrkj.back.vo.PackageInvalidVO;
import org.apache.commons.httpclient.util.HttpURLConnection;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lrkj.back.entity.TbAdvice;
import com.lrkj.back.entity.TbAffiche;
import com.lrkj.back.entity.TbShift;
import com.lrkj.back.entity.ZsPackageImformation;
import com.lrkj.back.entity.ZsYicipinKucun;
import com.lrkj.back.entity.ZsYicipinRukumingxi;
import com.lrkj.back.service.ZsPackageImformationService;
import com.lrkj.back.service.ZsYicipinKucunService;
import com.lrkj.back.service.ZsYicipinRukumingxiService;
import cn.com.cbons.mamisay.parent.exception.BusinessException;

import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/shift")
public class TbShiftController extends BaseController{
	@Autowired
	private TbShiftService shiftService;
	@Autowired
	private TbFileService fileService;
	@Autowired
	private ZsPackageImformationService packageInfoService;
	@Autowired
	private ZsYicipinKucunService ycpKucunService;
	@Autowired
	private TbPackageMubanService packagemubanService;
	@Autowired
	private TbAfficheService afficheService;
	@Autowired
	private ZsYicipinRukumingxiService rukumingxiService;
	@Autowired
	private TbAdviceService adviceService;

	//首页--回收查询
	@RequestMapping("/shiftList.do")
	public ModelAndView shiftList(String id, String searchTxt,HttpServletRequest request, HttpServletResponse response)throws Exception{
		Map<String,Object> map =new HashMap<String,Object>();
		TbEmployee employee = (TbEmployee)session.getAttribute("emp");
		PackageInvalidVO piVo = null;
		long oneday = 24*60*60*1000;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowtime = sdf.format(date);
		List<PackageInvalidVO> packinvalidVOs = new ArrayList<PackageInvalidVO>();
		//得到的是当前的时间
		long nowDate = sdf.parse(nowtime).getTime();
		//-----------------------查询文件
		if(StringUtils.isNotBlank(searchTxt)){
			map.put("shiftTitle", searchTxt.trim());//字段查询
		}
		map.put("shiftSort", 1);
		List<TbShift> shifts = shiftService.findAll(map);
		map.put("afficheSort", 2);
		List<TbAffiche> affiches = afficheService.findAllTbAfficheNoPage(map);
		//-------------------查询过期提醒--------------------------------
		//===================查询过期提醒(一次品)从入库明细表中查
		List<ZsYicipinRukumingxi> ycprRukumingxis = rukumingxiService.findAllNoPage(map);
		if (!ycprRukumingxis.isEmpty()) {
			Date shixiaoDate = null;
			for (ZsYicipinRukumingxi zsYicipinRukumingxi : ycprRukumingxis) {
				shixiaoDate = addDate(zsYicipinRukumingxi.getRukuCreatetime(), zsYicipinRukumingxi.getProductYouxiaoqiDays());
			    if (shixiaoDate.getTime()-nowDate <= 2*oneday) {
			    	piVo = new PackageInvalidVO();
			    	piVo.setInvalidDate(shixiaoDate);
			    	piVo.setPackageName(zsYicipinRukumingxi.getYcpKucun().getProductName());
			    	piVo.setPackTiaoma(zsYicipinRukumingxi.getProductId());
			    	piVo.setRukuDate(zsYicipinRukumingxi.getRukuCreatetime());
			    	packinvalidVOs.add(piVo);
				}
			}
		}
		//===================查询过期提醒(包)
		List<ZsPackageImformation> guoqibaoList = new ArrayList<ZsPackageImformation>();
//		Map<String, Object> map = new HashMap<String,Object>();
		map.put("baoRuku", 1);
		map.put("shoushu", "weifafang");
		//只针对通用包
		//配包关包时间，开始计算包有效期
		List<ZsPackageImformation> packageImformations = packageInfoService.findAll(map);

		//循环     一个包一个包的判断
		if (!packageImformations.isEmpty()) {
			ZsDabao dabao = null;
			Integer youxiaoqi = 0;
			long shixiaoriqi = 0l;
			String guanbaotime = "";
			Date invaDate = new Date();
			for (ZsPackageImformation zsPackageImformation : packageImformations) {
				//得到包的有效期
				piVo = new PackageInvalidVO();
				TbPackageMuban muban =null;
				muban = zsPackageImformation.getTbPackageMuban();
				if(muban!=null){
					dabao = muban.getZsDabao();
					if (dabao!=null) {
						youxiaoqi = dabao.getDabaoYouxiaoqiDays();
					}
					//得到包的有效期
					guanbaotime = sdf.format(zsPackageImformation.getPeibaoGuanbaoTime());
					//包的失效日期
					shixiaoriqi = sdf.parse(guanbaotime).getTime()+youxiaoqi*oneday+oneday/2;
					//得到当前日期
					long danqian = nowDate;
					//得到失效日期与当前日期的时间差
					long timecha = shixiaoriqi-danqian;
					invaDate = addDate(zsPackageImformation.getPeibaoGuanbaoTime(), zsPackageImformation.getTbPackageMuban().getZsDabao().getDabaoYouxiaoqiDays());
					if (timecha<=2*oneday) {
						if (!guoqibaoList.contains(zsPackageImformation)) {
							guoqibaoList.add(zsPackageImformation);
						}
						//配包关包时间代替入库时间
						piVo.setRukuDate(zsPackageImformation.getPeibaoGuanbaoTime());
						piVo.setPackTiaoma(zsPackageImformation.getPackageTiaoma());
						piVo.setPackageName(zsPackageImformation.getTbPackageMuban().getPackageName());
						piVo.setInvalidDate(invaDate);
						packinvalidVOs.add(piVo);
					}
				}

				
			}
		}
		//-----------------------库存预警-----------------------------------------
		//=======================库存预警(一次品)
		//一次品库存数量的提醒标准
		map.put("SYkucun", 15);
		List<KucunWarnVO> kucunWarnVOs = new ArrayList<KucunWarnVO>();
		KucunWarnVO kwVo = null;
		List<ZsYicipinKucun> ycpKucuns = ycpKucunService.findYicipinKucun(map);
		if (!ycpKucuns.isEmpty()) {
			for (ZsYicipinKucun zsYicipinKucun : ycpKucuns) {
				kwVo = new KucunWarnVO();
				kwVo.setTiaoma(zsYicipinKucun.getProductId());
				if (StringUtils.isBlank(zsYicipinKucun.getProductGuige())) {
					kwVo.setProductName(zsYicipinKucun.getProductName());
				}
				else {
					kwVo.setProductName(zsYicipinKucun.getProductName()+zsYicipinKucun.getProductGuige());
				}
				kwVo.setShengyuNum(zsYicipinKucun.getProductNum());
				kwVo.setLeibie(2);
				kucunWarnVOs.add(kwVo);
			}
		}
		if (!kucunWarnVOs.isEmpty()) {
			request.setAttribute("ycpKucun", kucunWarnVOs);
		}
		//=======================库存预警(包)
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("packageCategory", 1);
		//查找所有通用包模板
		List<TbPackageMuban> packageMubans = packagemubanService.findAllPackageNoPageList(map2);
		List<String> mubanIds = new ArrayList<String>();
		for (TbPackageMuban tbPackageMuban : packageMubans) {
			if (!mubanIds.contains(tbPackageMuban.getPackageId())) {
				mubanIds.add(tbPackageMuban.getPackageId());
			}
		}
		if (!mubanIds.isEmpty()) {
			map2.put("packageIdArr", mubanIds);
		}else {
			mubanIds.add("0");
			map2.put("packageIdArr", mubanIds);
		}
		map2.put("baoRuku", 1);
		map2.put("shoushu", "shengyubao");
		List<KucunWarnVO> kucunWarnVOs2 = packageInfoService.findRestbao(map2);
		if (!kucunWarnVOs2.isEmpty()) {
			TbPackageMuban packageMuban = null;
            for (KucunWarnVO kucunWarnVO : kucunWarnVOs2) {
            	kwVo = new KucunWarnVO();
				packageMuban = new TbPackageMuban();
				String aaa = kucunWarnVO.getTiaoma();
				System.out.println(aaa);
				String bbb = packageMuban.getPackageId();
            	packageMuban = packagemubanService.selectByPrimaryKey(kucunWarnVO.getTiaoma());
            	kwVo.setTiaoma(kucunWarnVO.getTiaoma());
            	kwVo.setLeibie(1);
            	kwVo.setProductName(packageMuban.getPackageName());
            	kwVo.setShengyuNum(kucunWarnVO.getShengyuNum());
            	//包库存数量的提醒标准
            	if (kwVo.getShengyuNum()<3) {
            		kucunWarnVOs.add(kwVo);
				}
			}
		}
		if (!kucunWarnVOs.isEmpty()) {
			request.setAttribute("ycpwarn", kucunWarnVOs);
		}
		if (guoqibaoList.size()!=0) {
			request.setAttribute("guoqibao", guoqibaoList);
		}
		if (!packinvalidVOs.isEmpty()) {
			request.setAttribute("gqb", packinvalidVOs);
		}else {
//			rtnMap.put("status", "false");
//			rtnMap.put("msg", "无快要失效的包");
		}
		//排班图片查询
		map2.put("afficheSort", 1);
		List<TbAffiche> affiche = afficheService.findAllTbAfficheNoPage(map2);
		if (affiche != null) {
			request.setAttribute("aff", affiche);
		}
		
		//查询投诉与建议
		Map<String, Object> adviceMap = new HashMap<String, Object>();
		if (employee != null) {
			adviceMap.put("adviceObject", employee.getEmployeeId());
		}
		List<TbAdvice> advices = adviceService.findAll(adviceMap);
		if (!advices.isEmpty()) {
			request.setAttribute("adviceList", advices);
		}
 		request.setAttribute("affiche", affiches);
 		request.setAttribute("shift", shifts);
		request.setAttribute("searchTxt", searchTxt==null?"":searchTxt);
		return new ModelAndView("/system/system_index");
	}

	@RequestMapping("/videoList.do")
	public ModelAndView videoList(String id, String searchTxt,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Integer pageNo = request.getParameter("pageIndex")==null? 1 :Integer.valueOf(request.getParameter("pageIndex"));
		Map<String,Object> map =new HashMap<String,Object>();
		if(StringUtils.isNotBlank(searchTxt)){
			map.put("shiftTitle", searchTxt.trim());//字段查询
		}
		map.put("shiftSort", 3);
		map.put("pageNo", pageNo);
		map.put("pageSize", Const.PAGE_SIZE);
		PageInfo<TbShift> page = shiftService.findAllTbShift(map);
		request.setAttribute("shiftList", page.getList());
		request.setAttribute("searchTxt", searchTxt==null?"":searchTxt);
		request.setAttribute("total", page.getPages());
		return new ModelAndView("/system/ziliaoshangchuan/wenjian");
	}

	//点添加和修改按纽用到的方法
	//kang de xin your gupiao
	//two hous xiaban housre shiftEdit setAttribute integer string httpservletRequest
	@RequestMapping("/shiftEdit.do")
	public ModelAndView shiftEdit(Integer lx,String wj, Integer id, HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		TbShift shift = null;
		TbFile file = null;
		if (lx==1) {
			file = (id == null) ? new TbFile() : fileService.selectByPrimaryKey(id);
		}else {
			shift = (id == null) ? new TbShift() : shiftService.selectByPrimaryKey(id);
		}
		request.setAttribute("shift", shift);
		request.setAttribute("leixing", lx);
		request.setAttribute("wj", wj);
		request.setAttribute("file", file);
		/*if (lx==1 && file != null) {
			return new ModelAndView("/system/wenku/file_edit");
		}else {*/
		return new ModelAndView("/system/wenku/shift_edit");
	}

	//修改  更新
	@RequestMapping("/shiftSave.do")
	@ResponseBody
	//this is my qiangping tmr
	public Map<Object,Object> shiftSave(TbShift shift, String lx, String wj, HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		System.out.println(wj.getClass());
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			shift.setShiftDate(new Date());
			Integer wjlx = null;
			if (StringUtils.isNotBlank(lx)) {
				wjlx = Integer.valueOf(lx);
			}
			if(shift.getShiftId() != null){
				shiftService.updateByPrimaryKey(shift);
			}else{
				if (wjlx == 1) {
					if (StringUtils.isNotBlank(wj) && !"null".equals(wj)) {
						shift.setShiftFile(Integer.valueOf(wj)); 
					}
					else {
						shift.setShiftFile(1);
					}
				}
				/*else {
					if (StringUtils.isNotBlank(wj) && !("null").equals(wj)) {
						shift.setShiftFile(Integer.valueOf(wj)); 
					}
				}*/
				shift.setShiftSort(1);
				shiftService.insert(shift);
			}
			rtnMap.put("status", "true");   
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	//删除
	@RequestMapping("/shiftDel.do")
	@ResponseBody
	public Map<Object,Object> shiftDel(HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			String ids = request.getParameter("id");
			String[] arraId = ids.split(",");
			for(String tid : arraId){
				shiftService.deleteByPrimaryKey(Integer.valueOf(tid));
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "删除成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "删除失败");
			e.printStackTrace();
		}
		return rtnMap;
	}

	@RequestMapping("/shipingEdit.do")
	public ModelAndView shipingEdit(Integer id, HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		TbShift shift = (id == null) ? new TbShift() : shiftService.selectByPrimaryKey(id);
		request.setAttribute("shift", shift);
		return new ModelAndView("/system/ziliaoshangchuan/shangchuan");
	}

	@RequestMapping("/shipinSelect.do")
	public ModelAndView shipinSelect(Integer id, String name, HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Integer shiftId = Integer.valueOf(id);
		TbShift shift = (id == null) ? new TbShift() : shiftService.selectByPrimaryKey(id);
		request.setAttribute("shift", shift);
		request.setAttribute("name", name);
		request.setAttribute("shiftId", shiftId);
		return new ModelAndView("/system/wenku/showvideo");
	}

	/**
	 * 点击文库
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	//首页--文库    （点击搜索）
	@RequestMapping("/wenkuList.do")
	public ModelAndView wenkuList(String tj, HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(tj)) {
			map.put("shiftname", tj);
		}
		List<TbFile> files = fileService.findAll(map);
		List<TbShift> shifts = shiftService.findAll(map);
		List<TbShift> tupian = new ArrayList<TbShift>();
		List<TbShift> shipin = new ArrayList<TbShift>();
		List<TbShift> wenjian = new ArrayList<TbShift>();
		for (TbShift tbShift : shifts) {
			if (tbShift.getShiftSort()==1) {
				tupian.add(tbShift);
			}
			if (tbShift.getShiftSort()==3) {
				shipin.add(tbShift);
			}
			if (tbShift.getShiftSort()==2) {
				wenjian.add(tbShift);
			}
		}
		request.setAttribute("file", files);
		request.setAttribute("tj", tj);
		request.setAttribute("shifts", shifts);
		request.setAttribute("tupian", tupian);
		request.setAttribute("shipin", shipin);
		request.setAttribute("wenjian", wenjian);
		return new ModelAndView("/system/wenku/wenku");
	}

	@RequestMapping("/deletebatch.do")
	@ResponseBody
	public Map<Object,Object> deletebatch(HttpServletRequest request,HttpServletResponse response) throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			List<String> shiftIds = new ArrayList<String>();
			List<String> fileIds = new ArrayList<String>();
			String[] ids = null;
			String[] ids1 = null;
			String[] ids2 = null;
			String[] ids3 = null;
			if (StringUtils.isNotBlank(request.getParameter("chk"))) {
				ids = request.getParameter("chk").split(",");
			}
			if (StringUtils.isNotBlank(request.getParameter("chk1"))) {
				ids1 = request.getParameter("chk1").split(",");
			}
			if (StringUtils.isNotBlank(request.getParameter("chk2"))) {
				ids2 = request.getParameter("chk2").split(",");
			}
			if (StringUtils.isNotBlank(request.getParameter("chk3"))) {
				ids3 = request.getParameter("chk3").split(",");
			}
			//删除文件夹
			boolean fb = true;
			if (ids!=null) {
				for (int i = 0; i < ids.length; i++) {
					if ("1".equals(ids[i])) {
						fb = false;
					}else {
						fileIds.add(ids[i]);						
					}
				}
			}
			//删除文
			if (ids1!=null) {
				for (int i = 0; i < ids1.length; i++) {
					shiftIds.add(ids1[i]);
				}
			}
			//删除视频
			if (ids2!=null) {
				for (int i = 0; i < ids2.length; i++) {
					shiftIds.add(ids2[i]);
				}
			}
			//删除图片
			if (ids3!=null) {
				for (int i = 0; i < ids3.length; i++) {
					shiftIds.add(ids3[i]);
				}
			}
			//图片批量删除
			if (!shiftIds.isEmpty()) {
				shiftService.deleteByBatch(shiftIds);
				rtnMap.put("msg", "删除成功");
				rtnMap.put("status", "true");
			}
			//文件批量删除
			if (fb) {
				if (!fileIds.isEmpty()) {
					fileService.deleteByBatch(fileIds);
					shiftService.deleteByfiles(fileIds);
					rtnMap.put("msg", "删除成功");
					rtnMap.put("status", "true");
				}
			}
			if (fb==false) {
				rtnMap.put("msg", "不可删除默认文件夹！");
				rtnMap.put("status", "false");
			}
		} catch (Exception e) {
			rtnMap.put("msg", "删除失败");
			rtnMap.put("status", "false");
			e.printStackTrace();
		}
		return rtnMap;
	}

	@SuppressWarnings("unused")
	@RequestMapping("/wenjianSelect.do")
	public Map<Object,Object> wenjianSelect(String id, HttpServletRequest request,HttpServletResponse response) throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object, Object>();
		TbShift shift = null;
		if (StringUtils.isNotBlank(id)) {
			shift = shiftService.selectByPrimaryKey(id);
		}
		//FIXME
		String cmd="rundll32 url.dll FileProtocolHandler file://D://zs_wkspace//zhuisu//src//main//webapp"+shift.getShiftImg();
//		String cmd="rundll32 url.dll FileProtocolHandler http://192.168.1.105:8080/zhuisu"+shift.getShiftImg();
		try {
			Process p = Runtime.getRuntime().exec(cmd);
			rtnMap.put("status","true");
		} catch (IOException e) {
			rtnMap.put("status","false");
			e.printStackTrace();
		}
		return rtnMap;
	}

	@RequestMapping("/xiazai.do")
	@ResponseBody
	public Map<Object,Object> downUrlTxt(String fileName,String fileUrl,String downPath ,HttpServletRequest request, HttpServletResponse response){
		//fileName(文件名)     fileUrl(文件路径)    downPath(下载路径)  
		Map<Object, Object> rtnMap = new HashMap<Object, Object>();
		try {
			fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
			fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
			response.setContentType("application/x-msdownload");  
	        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);  
			BufferedOutputStream qq = new BufferedOutputStream(response.getOutputStream());
			URL url = new URL(fileUrl);
			HttpURLConnection uc=  (HttpURLConnection)url.openConnection();
			
			uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true   
			uc.connect();   
			InputStream iputstream = uc.getInputStream();   
			System.out.println("file size is:"+uc.getContentLength());//打印文件长度   
			byte[] buffer = new byte[4*1024];   
			int byteRead = -1;      
			while((byteRead=(iputstream.read(buffer)))!= -1){   
				qq.write(buffer, 0, byteRead);
				
			}
			qq.flush();     
			iputstream.close();   
			rtnMap.put("msg", "下载成功");
			rtnMap.put("status", "true");
		} catch (Exception e) {   
			System.out.println("读取失败！");
			rtnMap.put("msg", "下载失败");
			rtnMap.put("status", "false");
			e.printStackTrace();   
		}
		return rtnMap;
//		writeByMapString(rtnMap);
	}
	
	@RequestMapping("/wenj.do")
	public ModelAndView wenj(String id ,HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		TbFile file = fileService.selectByPrimaryKey(id);
		map.put("shiftFile", id);
		List<TbShift> shifts = shiftService.findAll(map);
		request.setAttribute("shift", shifts);
		request.setAttribute("wj", id);
		request.setAttribute("file", file);
		return new ModelAndView("/system/wenku/file_pic");
	}
	
	public static Date addDate(Date date,long day) throws ParseException,BusinessException {
		long time = date.getTime(); // 得到指定日期的毫秒数
		day = day*24*60*60*1000; // 要加上的天数转换成毫秒数
		time+=day; // 相加得到新的毫秒数
		return new Date(time); // 将毫秒数转换成日期
	}
}